package com.xoa.service.crm.impl;

import com.xoa.dao.crm.ProductMapper;
import com.xoa.dao.crm.SupplierMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.crm.Product;
import com.xoa.model.crm.ProductExample;
import com.xoa.model.crm.Supplier;
import com.xoa.model.users.Users;
import com.xoa.service.crm.ProductService;
import com.xoa.util.*;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import sun.dc.pr.PRError;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by caoyin on 2019/5/29.
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductMapper productMapper;

    @Resource
    private SupplierMapper supplierMapper;

    @Resource
    private UsersMapper usersMapper;

    /**
     * 查询所有(不带参数)[导出功能接口]
     * @param page
     * @param pageSize
     * @param useFlag
     * @param map
     * @return
     */
    @Override
    public List<Product> selectByAll(Integer page, Integer pageSize, Boolean useFlag, Map map) {
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        map.put("page", pageParams);
        return productMapper.selectByExample(new ProductExample());
    }

    /**
     * 查询所有(不带参数)[导出功能接口]
     * @return
     */
    @Override
    public List<Product> selectAll() {
        return productMapper.selectAll();
    }
    /**
     * 查询所有(没被删除
     * @return
     */
    @Override
    public List<Product> selectProduct() {
        return productMapper.selectProduct();
    }

    /**
     * 数据回显接口
     * @param productId
     * @return
     */
    @Override
    public Product selectByPrimaryKey(Integer productId) {
        Product product = productMapper.selectByPrimaryKey(productId);
        Users userId = usersMapper.getUserId(product.getCreator());
        product.setCreator(userId.getUserName());
        return product;
    }

    /**
     * 模糊查询及分页
     * @param page
     * @param pageSize
     * @param useFlag
     * @param map
     * @return
     */
    @Override
    public List<Product> selectByCondition(Integer page, Integer pageSize, Boolean useFlag, Map map) {
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        map.put("page", pageParams);
        List<Product> products = productMapper.selectByCondition(map);
        ArrayList<Product> list = new ArrayList<>();
        for (Product p :products) {
            String creator = p.getCreator();
            String username = usersMapper.getUsernameByUserId(creator);
            p.setCreator(username);
            list.add(p);
        }
        return list;
    }

    /**
     * 根据主键id进行删除(逻辑删除)
     * 删除标志(isDeleted)：1-已删除;0-未删除(默认未删除)
     * @param productId
     * @return
     */
    @Override
    public int deleteByPrimaryKey(Integer productId) {
        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        //逻辑删除 修改状态
        Product product = productMapper.selectByPrimaryKey(productId);
        product.setIsDeleted(Byte.valueOf("1"));
        //删除人
        product.setDeleteUser(users.getUserId());
        //删除时间
        product.setDeleteTime(new Date());
        return productMapper.updateByPrimaryKeySelective(product);
    }

    /**
     * 添加产品数据
     * @param product
     * @return
     */
    @Override
    public int insertProduct(Product product) {
        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        //创建时间
        product.setCreateTime(new Date());
        //创建人
        product.setCreator(users.getUserId());
        //将新增数据删除标记默认设置为0
        product.setIsDeleted(Byte.valueOf("0"));
        return productMapper.insertSelective(product);
    }

    /**
     * 插入全部的数据
     * @param product
     * @return
     */
    @Override
    public int insertSelective(Product product) {
        return productMapper.insertSelective(product);
    }

    /**
     * 更新数据(根据产品id)
     * @param product
     * @return
     */
    @Override
    public int updateByPrimaryKeySelective(Product product){
        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        //更新时间
        product.setUpdateTime(new Date());
        //更新人
        product.setUpdator(users.getUserId());
        return productMapper.updateByPrimaryKeySelective(product);
    }

    /**
     * 产品信息表导出功能
     * @param request
     * @param response
     * @param product
     * @param beginDate
     * @param isExport
     * @return
     */
    @Override
    public ToJson<Product> queryExportProduct(HttpServletRequest request, HttpServletResponse response, Product product, String beginDate, String isExport) {
        ToJson<Product> json = new ToJson<Product>();
        try {
            List<Product> productList= productMapper.selectAll();
            List<Product> products=new ArrayList<>();
            for (Product data : productList) {
                if (data.getIsDeleted() != 1) {
                    if (data.getSupplierId() != null) {
                        Supplier supplier = supplierMapper.selectByPrimaryKey(data.getSupplierId());
                        data.setSupplierName(supplier.getSupplierName());
                    }
                    //处理创建时间格式
                    if(data.getCreateTime()!=null){
                        data.setCreateTimeStr(DateFormat.getStrDate(data.getCreateTime()));
                        products.add(data);
                    }
                }
            }
            //条件判断[后端拼接条件进行判断]
            if ("yes".equals(isExport)){
                // 设置Excel表头标题
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("产品信息表", 11);
                // 设置Excel表的字段名
                String[] secondTitles = {"产品名称", "提供商名称","产品类型","计量单位","成本价(元)","销售价(元)","产品库存","规格型号","创建人","创建时间"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                // 字段名对应的实体类属性名称
                String[] beanProperty = {"productName","supplierName","type","meteringUnit","cost","price","stock","specification","creator","createTimeStr"};
                HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, products, beanProperty);
                ServletOutputStream out = response.getOutputStream();
                // 设置Excel表的导出名称
                String filename = "产品信息表.xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }

    /**
     * 产品信息表导入功能
     * @param request
     * @param response
     * @param file
     * @return
     */
    @Override
    public ToJson<Product> queryImportProduct(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        //获取当前的登陆信息
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        ToJson json = new ToJson(1,"error");
        try {
            String fileName = null;
            if (file!=null){
                fileName=file.getOriginalFilename();
            }
            if (fileName!=null&&(fileName.endsWith(".xls")||fileName.endsWith(".xlsx"))){
                int count=0;
                int flag=0;
                Integer uId= (Integer) request.getSession().getAttribute("uid");
                List<Product> list=new ArrayList<>();

                ExcelRead excelRead=new ExcelRead();
                List<Map<String,Object>> readList=excelRead.readExcel(file);
                for (Map<String, Object> map : readList) {
                    if (!"".equals(map.get("产品名称"))&&!"".equals(map.get("产品名称"))){
                        Product product=  new Product();
                        product.setProductName(map.get("产品名称").toString());
                        product.setType(map.get("产品类型").toString());
                        product.setMeteringUnit(map.get("计量单位").toString());
                        product.setCost(new BigDecimal(map.get("成本价").toString()));
                        product.setPrice(new BigDecimal(map.get("销售价").toString()));
                        product.setStock(Integer.valueOf(map.get("产品库存").toString()));
                        product.setSpecification(map.get("规格型号").toString());
                        product.setCreator(users.getUserId());
                        product.setCreateTime(new Date());
                        list.add(product);
                        count++;
                    }
                }
                if (count>0){
                    flag=productMapper.importProduct(list);
                }
                if (flag>0){
                    json.setFlag(0);
                    json.setMsg("导入成功");
                    json.setTotleNum(count);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }



}
